<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请人')" prop="userId">
            <UserSelect v-model="form.userId" :placeholder="$t('申请人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请人所属公司')" prop="company">
            <tree-select
              v-model="form.company"
              node-key="id"
              :default-expand-all="true"
              :data="companyOptions"
              :placeholder="$t('请选择')"
            >
              <label
                slot="option-label"
                slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }"
                :class="labelClassName"
              >
                {{ $t(node.label) }}
                <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
              </label>
            </tree-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请人所属部门')" prop="department">
            <!--            <DeptSelect v-model="form.department" :placeholder="$t('申请人所属部门')" />-->
            <dept-select
              v-model="form.department"
              :default-expand-all="true"
              :data="deptOptions"
              :placeholder="$t('请选择')"
            >
              <label
                slot="option-label"
                slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }"
                :class="labelClassName"
              >
                {{ $t(node.label) }}
                <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
              </label>
            </dept-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('签约主体类型')" prop="contractMainType">
            <dictSelect
              v-model="form.contractMainType"
              :clearable="true"
              dictionary="contract_subject_type"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('签约主体')" prop="contractMain">
            <MainBodySelect
              v-model="form.contractMain"
              :parameters="form.contractMainType"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合同名称')" prop="contractName">
            <el-input v-model="form.contractName" :placeholder="$t('合同名称')" show-word-limit :maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合同金额') + $t('金额单位')" prop="contractAmount">
            <Money v-model="form.contractAmount" unit="w" :placeholder="$t('合同金额')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否用印')" prop="isSeal">
            <el-radio-group v-model="form.isSeal">
              <el-radio
                v-for="dict in isSealOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('合同摘要')" prop="abstracts">
            <el-input v-model="form.abstracts" type="textarea" :placeholder="$t('合同摘要')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
      </el-row>

      <!--预算明细-->
      <div class="area-header">
        <span class="area-header-title">{{ $t('预算明细') }}</span>
      </div>
      <el-table
        :data="form.dealBudgetDetailsList"
        border
        class="nowrapTable formTable "
        style="overflow: auto;"
        :summary-method="summaryMethod"
        show-summary
      >
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('序号') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item
              type="index"
              v-html="scope.$index + 1"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" min-width="150px">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('科目代码') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealBudgetDetailsList.' + scope.$index + '.subjectCode'" :rules="dealBudgetDetailsListRules.subjectCode">
              <el-input v-model="scope.row.subjectCode" :placeholder="$t('科目代码')" disabled />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('科目名称')" align="center" min-width="180px">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('科目名称') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealBudgetDetailsList.' + scope.$index + '.costBudgetArray'" :rules="dealBudgetDetailsListRules.costBudgetArray">
              <el-cascader
                v-model="scope.row.costBudgetArray"
                :options="dealCostBudgetList"
                clearable
                @change="payTypeChange(scope.$index)"
              >
                <template slot-scope="{ node, data }">
                  <span>{{ $t(data.subjectName) }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('金额') + $t('金额单位')" align="center" min-width="140">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('金额') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealBudgetDetailsList.' + scope.$index + '.amount'" :rules="dealBudgetDetailsListRules.amount">
              <Money v-model="scope.row.amount" unit="w" @change="percentageCalculation" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="!otherBtnHide" fixed="right" :label="$t('操作')" align="center">
          <template slot-scope="scope">
            <el-button v-hasPermi="['fixedAssets:BudgetDetails:remove']" size="small" type="text" icon="el-icon-delete" @click="delHandle(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!otherBtnHide" class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addDetails">{{ $t("添加明细") }}</el-button>
      </div>
      <!-- 附件列表 -->
      <FileTable :list.sync="form.fileList" data-type="deal_fixed_assets_contract" :business-id="form.dealId" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="deal:fixedAssets" />
    </div>
  </div>
</template>

<script>
import {
  saveDealFixedAssetsContract,
  getDealFixedAssetsContract,
  delDealBudgetDetails
} from '@/api/deal/fixedAssets/dealFixedAssetsContract'
    import MainBodySelect from '@/components/MainBodySelect'
    import { treeselect } from '@/api/system/dept'
    import TreeSelect from '@/components/TreeSelect'
import { listTreeInDealCostBudget } from '@/api/deal/fixedAssets/dealCostBudget'
    export default {
      components: {
        MainBodySelect,
        TreeSelect
      },
        data() {
            return {
                // 表单参数
                form: {
                  // 预算明细
                  dealBudgetDetailsList: []
                },
                // 表单校验
                rules: {
                  actTitle: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }],
                  userName: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }],
                  company: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }],
                  department: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }],
                  contractName: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }],
                  contractMainType: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }],
                  contractMain: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }],
                  contractAmount: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }],
                  isSeal: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }]
                },
                dealBudgetDetailsListRules: {
                  costBudgetArray: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }],
                  amount: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }]
                },
                // 遮罩层
                loading: false,
                // 操作按钮默认不展示
                buttonShow: true,
                // 是否隐藏其它按钮
                otherBtnHide: false,
                // 单选
                isSealOptions: [],
                // 公司树
                companyOptions: [],
                // 部门树
                deptOptions: [],
                dealCostBudgetList: []
            }
        },
        created() {
            this.$bus.$emit('async_done')
            this.getDicts('sys_yes_no').then(response => {
              this.isSealOptions = response.data
            })
            treeselect({ 'deptType': 'GS' }).then(response => {
              this.companyOptions = response.data
            })
            listTreeInDealCostBudget({ dealId: this.$route.query.id }).then(response => {
              var data = response.rows
              // 国际化
              data.forEach(item => {
                item.label = this.$t(item.label)
                item.children.forEach(item2 => {
                  item2.label = this.$t(item2.label)
                })
              })
              this.dealCostBudgetList = data
            })
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                if (data != null && data.id !== undefined) {
                    getDealFixedAssetsContract(data.id).then(response => {
                        this.form = response.data
                        for (let i = 0; i < this.form.dealBudgetDetailsList.length; i++) {
                          const type = this.form.dealBudgetDetailsList[i]
                          this.$set(this.form.dealBudgetDetailsList[i], 'costBudgetArray', [])
                          this.form.dealBudgetDetailsList[i].costBudgetArray.push(type.costBudgetOne)
                          this.form.dealBudgetDetailsList[i].costBudgetArray.push(type.costBudgetTwo)
                          this.payTypeChange(i)
                        }
                        this.loading = false
                    }).catch(() => {
                        this.loading = false
                    })
                } else {
                    this.reset()
                    this.loading = false
                }
            },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    dealId: this.$route.query.id,
                    actTitle: undefined,
                    userId: this.$store.state.user.userId,
                    company: undefined,
                    department: undefined,
                    contractName: undefined,
                    contractMainType: undefined,
                    contractMain: undefined,
                    contractAmount: undefined,
                    isSeal: undefined,
                    abstracts: undefined,
                    actId: undefined,
                    actStatus: undefined,
                    createBy: undefined,
                    createTime: undefined,
                    updateBy: undefined,
                    updateTime: undefined,
                    delFlag: undefined
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                    this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
            /** 提交按钮 */
            submitForm(type) {
                return new Promise((resolve, reject) => {
                  this.$refs['form'].validate(valid => {
                    // 验证数据
                    if (valid) {
                      // 弹出遮罩层
                      this.loading = true
                      // 保存数据
                      saveDealFixedAssetsContract(this.form).then(response => {
                        if (response.code === 200) {
                          // 点击的按钮是保存并启动流程
                          if (type === 'process') {
                            // 启动流程
                            this.startProcess(response.data.id)
                            // 点击的仅保存
                          } else {
                            this.msgSuccess(this.$t('保存成功'))
                            // 关闭form页面
                            this.closeForm()
                          }
                          resolve()
                        } else {
                          this.msgError(response.msg)
                          this.loading = false
                          reject()
                        }
                      })
                    } else {
                      reject()
                      this.locationError(document)
                    }
                  })
                }).catch(() => {
                    this.loading = false
                })
           },
            // 启动流程
           startProcess(dataId) {
               this.loading = false
               // 启动流程时候传入的参数
               const processData = {}
               // 待办标题
               processData.title = this.form.actTitle
               // 业务表名
               processData.dataTable = 'deal_fixed_assets_contract'
               // 业务ID
               processData.dataId = dataId
               // 业务表单地址(待办页面需要打开的页面)
               processData.formPath = '@/views/deal/fixedAssets/contract/dealFixedAssetsContractForm'
               // 菜单标识(根据菜单标识判断的走哪个流程)
               processData.menuKey = 'deal_fixed_assets_contract'
               this.startProcessByMenu(processData, () => {
                   this.form.actStatus = 'D'
                   this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
                   this.closeForm()
               })
           },
          // 添加预算明细
          addDetails() {
            const row = {
              id: undefined,
              contractId: '',
              costBudgetId: undefined,
              costBudgetArray: [],
              subjectCode: '',
              subjectName: '',
              amount: 0
            }
            if (!(this.form.dealBudgetDetailsList instanceof Array)) {
              this.$set(this.form, 'dealBudgetDetailsList', [])
            }
            this.$nextTick(() => {
              this.form.dealBudgetDetailsList.push(row)
            })
          },
          // 删除预算明细
          delHandle(index, row) {
            const that = this
            const id = row.id
            if (id !== undefined && id !== '' && id != null) {
              this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              }).then(function() {
                return delDealBudgetDetails(id).then(response => {
                  if (response.code === 200) {
                    that.form.dealBudgetDetailsList.splice(index, 1)
                    that.percentageCalculation()
                    return that.msgSuccess(that.$t('删除成功'))
                  }
                })
              })
            } else {
              that.form.dealBudgetDetailsList.splice(index, 1)
              that.percentageCalculation()
            }
          },
          // 获取明细合计
          summaryMethod() {
            let sum = 0
            this.form.dealBudgetDetailsList.forEach(item => {
              sum += +item.amount
            })
            return sum
          },
          // 计算合计是总额
          getSummaries() {
            let sum = 0
            this.form.dealBudgetDetailsList.forEach(item => {
              sum += item.amount
            })
            this.$set(this.form, 'contractAmount', sum)
            return sum
          },
          // 计算付款主体的百分比
          percentageCalculation() {
            var temp = 0
            this.form.dealBudgetDetailsList.forEach(item => {
              temp += item.amount
            })
            var noLastRatio = 0.0
            this.form.dealBudgetDetailsList.forEach((item, index) => {
              var ratioTemp = (item.amount / temp) * 100
              if (isNaN(ratioTemp)) {
                ratioTemp = 0
              }
              item.ratio = ratioTemp.toFixed(4)
              if (this.form.dealBudgetDetailsList === null) {
                this.form.dealBudgetDetailsList = ''
              }
              if (index === this.form.dealBudgetDetailsList.length - 1 && !isNaN(noLastRatio)) {
                if (parseFloat(item.ratio) <= 0) {
                  item.ratio = 0
                } else {
                  item.ratio = (100.0000 - noLastRatio).toFixed(4)
                }
              } else {
                noLastRatio += parseFloat(item.ratio)
              }
            })
            this.getSummaries()
          },
          // 付款类型的onchang时间
          payTypeChange(value) {
            let vals = this.form.dealBudgetDetailsList[value].costBudgetArray
            this.form.dealBudgetDetailsList[value].subjectCode = ''
            this.dealCostBudgetList.forEach(item => {
              if (vals === undefined) {
                var temp = []
                temp.push('-1')
                vals = temp
              }
              item.children.forEach(itemTwo => {
                if (itemTwo.id === vals[1]) {
                  this.form.dealBudgetDetailsList[value].subjectCode = itemTwo.subjectCode
                }
              })
            })
          }

        }

    }
</script>
